package com.bike.controller.authc;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bike.cache.UserCache;
import com.bike.controller.BaseController;
import com.bike.entity.HhOrder;
import com.bike.service.impl.HhAgentServiceImpl;
import com.bike.service.impl.HhBusinessServiceImpl;
import com.bike.service.impl.HhBusinessUserServiceImpl;
import com.bike.service.impl.HhOrderServiceImpl;
import com.bike.util.Constant;
import com.bike.util.PageData;
import com.topit.show.aliapi.AliConstant;
import com.topit.show.core.util.SignUtil;
import com.topit.show.core.util.XmlUtil;

 
@Controller
@RequestMapping(value="/authcPay")
public class HhAuthcPayController extends BaseController {
	
		@Autowired
		private HhAgentServiceImpl  hhAgentService;
		@Autowired
		private HhBusinessServiceImpl  hhBusinessServiceImpl;
		@Autowired
		private HhBusinessUserServiceImpl  businessUserServiceImpl;
		@Autowired
		private HhOrderServiceImpl  hhOrderServiceImpl;
		@Autowired
		private UserCache  usercache;
	
		/**
		 * 微信 扫码h5支付回调
		 */
		@RequestMapping("wx")
		@ResponseBody
		public String sendCode(HttpServletRequest request,Model model){
			PageData msgMap=new PageData();
			try {
				msgMap = XmlUtil.parseXmlToPageData(request);//将异步通知中收到的所有参数都存放到map中
				Long orderId=msgMap.getLong("out_trade_no");
				 
				HhOrder hhOrder=hhOrderServiceImpl.selectByHhOrderId(orderId);
				
				String success="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				if(hhOrder==null||hhOrder.getPayStatus()==Constant.pay){
					return success;
				}
				 
				String sign = msgMap.getString("sign");
				msgMap.remove("sign");
				if (sign.equals(SignUtil.getSign(msgMap))) {
					//签名验证通过
					logger.debug("签名验证通过-------------");
					if ("SUCCESS".equals(msgMap.get("return_code"))) {
						//校验金额
						logger.debug("校验金额是否正确-------------"+(hhOrder.getTotalPrice().multiply(new BigDecimal("100")).doubleValue()!=msgMap.getDouble("total_fee")));
						if(hhOrder.getTotalPrice().multiply(new BigDecimal("100")).doubleValue()!=msgMap.getDouble("total_fee")){
							return success;
						}
						msgMap.put("channel", Constant.wxOrder);
						msgMap.put("payway", Constant.wxChannel);
						 hhOrderServiceImpl.updateOrderSuccess(msgMap, hhOrder);
						return success;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}
		/**
		 * 支付宝回调
		 * @param request
		 * @param model
		 * @return
		 */
		@RequestMapping("ali")
		@ResponseBody
		public String login(HttpServletRequest request,Model model){
			PageData pd=PageData.getPageDataByPage(request);//将异步通知中收到的所有参数都存放到map中
			
			Long orderId=pd.getLong("out_trade_no");
			HhOrder hhOrder=hhOrderServiceImpl.selectByHhOrderId(orderId);
			if(hhOrder==null||hhOrder.getPayStatus()==Constant.pay){
				return "success";
			}
			boolean signVerified;
			try {
				signVerified = AlipaySignature.rsaCheckV1(pd, AliConstant.aliPublicKey, AliConstant.CHARSET, AliConstant.SIGN_TYPE);
				if(signVerified){
					// TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
					pd.put("channel", Constant.aliOrder);
					pd.put("payway", Constant.aliChannel);
					//校验金额
					if(!hhOrder.getTotalPrice().toString().equals(pd.getString("buyer_pay_amount"))){
						return "success";
					}
					
					hhOrderServiceImpl.updateOrderSuccess(pd, hhOrder);
					return  "success";
				}else{
				// TODO 验签失败则记录异常日志，并在response中返回failure.
				}
			} catch (AlipayApiException e) {
				e.printStackTrace();
			}//调用SDK验证签名
			 
			return  "error";
		}
	 
	 
}
